﻿using ine.Extensions;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;

namespace ine
{
    public partial class App : Application
    {
        public App()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
        }

        private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            new Facade().Handle(e.Exception, "Dispatcher caused unhandled exception");
            e.Handled = true;
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            new Facade().Handle((Exception)e.ExceptionObject, "AppDomain caused unhandled exception");
        }

        private void HandleDragWindow(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                sender.ForWindow(window => window.DragMove());
            }
        }

        private void HandleCloseButton(object sender, RoutedEventArgs e)
        {
            sender.ForWindow(window => window.Close());
        }

        private void HandleMinimizeButton(object sender, RoutedEventArgs e)
        {
            sender.ForWindow(window => window.WindowState = WindowState.Minimized);
        }

        private void HandleListViewLoaded(object sender, RoutedEventArgs e)
        {
            ((ListView)VisualTreeHelper.GetParent((DependencyObject)e.Source)).Autofill();
        }

        private void HandleEscape(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                sender.ForWindow(window =>
                {
                    if (Object.ReferenceEquals(window, this.MainWindow) == false)
                    {
                        window.Close();
                    }
                });
            }
        }

        private void HandleWindowInitialize(object sender, EventArgs e)
        {
            sender.ForWindow(window =>
            {
                window.KeyDown += this.HandleEscape;
            });
        }
    }
}
